package com.ruoyi.quartz.thread;

import com.ruoyi.bizsys.domain.ExtMonnifyOrder;
import com.ruoyi.bizsys.domain.RepaymentOrder;
import com.ruoyi.bizsys.service.IRepaymentOrderService;
import com.ruoyi.business.service.IBRepaymentService;
import com.ruoyi.common.core.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.Callable;

@Slf4j
public class TransactionTaskThread implements Callable {

    private String threadName;
	private String redisName;
	private RedisCache redisCache;

    private IBRepaymentService iBRepaymentService;
	private IRepaymentOrderService iRepaymentOrderService;

    public TransactionTaskThread(String threadName, String redisName,
						  IBRepaymentService iBRepaymentService, RedisCache redisCache,IRepaymentOrderService iRepaymentOrderService) {
		super();
		this.threadName = threadName;
		this.redisName = redisName;
		this.redisCache = redisCache;
		this.iBRepaymentService = iBRepaymentService;
		this.iBRepaymentService = iBRepaymentService;
	}

	@Override
	public String toString() {
		return "BatchJobThread [threadName=" + threadName+ ", redisName=" + redisName + "]";
	}

	@Override
    public Object call() throws Exception {
        String result = ":success";
		log.info(this.threadName+"=======[START]===" + this.toString());

		List<ExtMonnifyOrder> list = redisCache.getCacheList(this.redisName);
		log.info("共有{}个订单号需要执行", list.size());
		
        for (ExtMonnifyOrder order : list) {
        	log.info("内部订单号{}开始执行跑批操作", order.getPaymentReference());

			boolean b = iBRepaymentService.checkTransactionIsSuccess(order.getPaymentReference(), order.getTransactionReference());

			if(!b){
				RepaymentOrder repaymentOrder = new RepaymentOrder();
				repaymentOrder.setRepaymentNo(order.getPaymentReference());
				repaymentOrder.setRepayStatus(1);
				List<RepaymentOrder> repaymentOrders = iRepaymentOrderService.selectRepaymentOrderList(repaymentOrder);

				if(repaymentOrders==null || repaymentOrders.size()==0){
					//没完成时  改为repaymentOrder改为10；
					iBRepaymentService.closeByRepayemntNo(order.getPaymentReference());
				}

			}

			log.info("内部订单号{}执行跑批操作正常结束", order.getPaymentReference());
        }

		redisCache.deleteObject(this.redisName);
        
        log.info(this.threadName+"=======[END]===run result:" + result);
        return threadName + result;
    }
}